<?php
/**
 * 从内容表中读取文章分类前序遍历后，构造数组并生成缓存 
 * article_class
 */
function class_cache() {
    global $_TABLES;
    $tbl_main   = $_TABLES['article_class'];
    $where  = "WHERE 1 ";

    $conn   = & get_db_conn();
    $sql    = "SELECT * 
                FROM $tbl_main 
                $where
            ORDER BY pid ASC,
                     order_no ASC, 
                     cid ASC ";
    $arr_class = array();
    $arr_class[]    = array(
            '__id__'        => 0,
            '__parent_id__' => -1,
            '__islast__'    => 1,
            '__text__'      => '根节点',
        );

    $i  = 0;
    $rs = & $conn->Execute($sql);
    if(!$rs->EOF) {
        while (!$rs->EOF) {
            $cid    = $rs->fields['cid'];
            $pid    = $rs->fields['pid'];
            $cname  = htmlspecialchars($rs->fields['cname']);
            $cata_dir   = $rs->fields['cata_dir'];
            $cata_id    = $rs->fields['cata_id'];
            $cata_type  = $rs->fields['cata_type'];
            $cata_keylang = trim($rs->fields['cata_keylang']);
            $defparam   = $rs->fields['defparam'];

            $arr_class[]    = array(
                '__id__' => $cid,
                '__parent_id__' => $pid,
                '__text__' => $cname,
                '__cur_node_nav__' => '',
                '__have_sub__' => 0,
                '__islast__' => 0,


                'cid'   => $cid,
                'pid'   => $pid,
                'cname' => $cname,
                'cata_dir' => $cata_dir,
                'cata_id'  => $cata_id,
                'cata_type'  => $cata_type,
                'cata_keylang' => $cata_keylang,


                'img'       => $rs->fields['img'],
                'redirect'  => $rs->fields['redirect'],
                'url'       => $rs->fields['url'],
                'order_no'  => $rs->fields['order_no'],

					
                'showid'	=> $rs->fields['showid'],

                'seo_title'     => $rs->fields['seo_title'],
                'seo_keywords'  => $rs->fields['seo_keywords'],
                'seo_description' => $rs->fields['seo_description'],



                'description'   => $rs->fields['description'],
                'record_count_all'  => $rs->fields['record_count_all'],
                'record_count_only' => $rs->fields['record_count_only'],

                'defparam' => $defparam,
                );
            $rs->MoveNext();
            if($i > 0) {
                // 如果当前读取的组的父节点已经不是上一个一样的了，那上一个就是最后一个节点了
                ($arr_class[$i]['__parent_id__'] != $arr_class[$i-1]['__parent_id__']) && $arr_class[$i-1]['__islast__'] = 1;
            }
            $i ++;
        }
        // 最后再判断一次看倒数第二个是否是最后一个节点
        ($arr_class[$i]['__parent_id__'] != $arr_class[$i-1]['__parent_id__']) && $arr_class[$i-1]['__islast__'] = 1;
        // 最后一个肯定是该父节点的最后一个节点
        $arr_class[$i]['__islast__'] = 1;
    }

    // 按树型要求前序遍历该分类数组，生成分类缓存
    global $__arrtree, $arrtree_pt;
    $GLOBALS['__arrtree']   = & $arr_class;
    tree_pt(0);

    // +----------------------------------------------------------+ //
    // 缓存生成开始
    global $cfg_cache;
    $file_name  = $cfg_cache['cache_abspath'] . '/' . $cfg_cache['content_class_cache_filename'];
    $str_var    = "<"."?php\r\n" . 
                "\$" . $cfg_cache['content_class_cache_var'] . " = " . var_export_str($GLOBALS['__arrtree_pt']) . ";\r\n".
                "?".">";
    write_to_file($file_name, $str_var);
    // 缓存生成完毕
    // +----------------------------------------------------------+ //
}


/**
 * 由于分类是树形结构，采用表处理的时候我们需要决定默认载入多少
 *
 * $level 载入前几级
 */
function cli($level = 2, $page_size = ADM_PAGESIZE){
    global $cfg_cache;
    $view_var   = array();

    // 包含class变量
    $file_name  = $cfg_cache['cache_abspath'] . '/' . 
                $cfg_cache['content_class_cache_filename'];
    $class_var  = $cfg_cache['content_class_cache_var'];
    if(file_exists($file_name)) {
        require($file_name);
    } else {
        $$class_var = array();
    }

    // 过滤掉不是本栏目的分类
    $cata_id    = @(int)$_GET['cata'];
    if($cata_id > 0) {
        $views['class_list']    = array();
        $icount = 0;
        foreach($$class_var as $v) {
            if($v['cata_id'] == $cata_id) {
                // 其余结点前的为第一个“空白”
                // 第一个结点的第一个为“└”
                if($icount == 0) {
                    $v['__node_pre'][0] = 'sub_two';
                } else {
                    $v['__node_pre'][0] = 'zero';
                }
                $views['class_list'][] = $v;
                $icount ++;
            }
        }
    } else {
        $views['class_list']    = $$class_var;
    }
    return $views;
}


function cread($cid, $pid) {
    global $_TABLES, $G_big_integer;
    $cid    = @(int)$cid;
    $pid    = @(int)$pid;

    $view_var   = array();
    $tbl_main  = $_TABLES['article_class'];
    $conn   = & get_db_conn();

    if($cid > 0) {
        // 修改
        $sql    = "SELECT c.*,
                    pc.cname AS pcname

                    FROM $tbl_main AS c
               LEFT JOIN $tbl_main AS pc
                      ON c.pid = pc.cid
                   WHERE c.cid = $cid";
        $view_var   = $conn->GetRow($sql);
    } else {
        // 新增
        $sql    = "SELECT pc.cname AS pcname
                    FROM $tbl_main AS pc
                    WHERE pc.cid = $pid";
        $rs     = $conn->GetRow($sql);
        $pcname = (is_array($rs) && sizeof($rs) > 0) ? $rs['pcname'] : '';
        $view_var   = array(
            'cid'   => 0,
            'pid'   => $pid,
            'cid_path'  => '',
            'order_no'  => $G_big_integer,
            'cname'     => '',
            'img'       => '',
            'description'   => '',
            'redirect'      => '',
            'url'           => '',
            'record_count_all'  => 0,
            'record_count_only' => 0,
            'pcname'    => $pcname,
            'seo_title' => '',
            'seo_keywords' => '',
            'seo_description' => '',
            'param' => false,
            );
    }
    return $view_var;
}


function crequest() {
    global $G_big_integer;

    $data = $_POST['class'];

    $data['cid'] = @(int)$data['cid'];
    $data['pid'] = @(int)$data['pid'];
    $data['order_no'] = @(int)$data['order_no'];
    $data['delimg'] = @(int)$data['delimg'];
    if($data['order_no'] < 1 || $data['order_no'] > $G_big_integer) $data['order_no'] = $G_big_integer;

    if($data['url'] == '') $data['redirect'] = '';

    $rule   = array(
        'cname'         => 'i_string|len:1:100', 
        'description'   => 'i_empty|len:0:255', 
        );
    $def_err    = array(
        'cname'         => '“栏目名称”必须填写，且长度必须在1～100个字符之间！', 
        'description'   => '“栏目描述”长度必须不能超过255个字符！', 
        );

    $result = data_validator($data, $rule, $def_err);
    if($result !== true) {
        foreach($result as $v) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                $v, 
                __FILE__,
                __LINE__);
        }
    }

    if($GLOBALS['ERR']->Count > 0)
        return false;
    else {
        global $mod, $G_abs_includes;
        require($G_abs_includes . '/upload.php');
        $up = upload_files($mod, 'class');
        if(!$data['delimg'] && $up) {
            $data['img'] = $up['classimg']['destfile'];
            $data['imgaid'] = $up['classimg']['aid'];
        } else {
            $data['img'] = '';
            $data['imgaid'] = 0;
        }
        return $data;
    }
}


function cadd() {
    global $_TABLES, $timestamp, $class_var;
    $tbl_main   = $_TABLES['article_class'];
    $tbl_ass1   = $_TABLES['attachments'];

    $result = crequest();
    if($result !== false) {
        $conn   = & get_db_conn();

        // 得到父节点，判断父节点是否存在，不存在将此节点安放在根节点处
        $sql = "SELECT cid, cname FROM $tbl_main WHERE cid = '{$result['pid']}' ";
        $rs = $conn->GetOne($sql);
        if(!$rs) $pid    = 0;


        // 同一个父节点下判断是否存在同名节点
        $sql = "SELECT COUNT(*) AS rs_count FROM $tbl_main WHERE pid = '{$result['pid']}' AND cname = '{$result['cname']}' ";
        $rs = $conn->GetOne($sql);
        if($rs) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                '父节点下已经存在名为<FONT COLOR=\"red\">' . $result['cname'] . '</FONT>的分类，无法当前添加操作！', 
                __FILE__,
                __LINE__);
            return false;
        }

        // 得到一级栏目ID
        // 只要不是新增一级栏目都可以用父id得到一级栏目ID
        if($result['pid'] > 0) $result['cata_id'] = find_onelevel_id($result['pid'], $GLOBALS[$class_var]);
        if($conn->AutoExecute($tbl_main,$result,'INSERT')) {
            $cid = $conn->Insert_ID();
            if($result['pid'] == 0) {
                $conn->Execute("UPDATE $tbl_main SET cata_id = '$cid' WHERE cid = '$cid' ");
            }
            if($result['imgaid'] > 0) {
                $conn->Execute("UPDATE $tbl_ass1 SET item_id = '$cid' WHERE aid = '{$result['imgaid']}' ");
            }
            class_cache();
            return $cid;
        }
    }
    return false;
}

function cmodify() {
    global $_TABLES, $timestamp, $basic_config, $class_var;
    global $mod;
    $tbl_main   = $_TABLES['article_class'];
    $tbl_ass1   = $_TABLES['attachments'];


    $result = crequest();
    if($result !== false) {
        $conn   = & get_db_conn();


        // 得到父节点，判断父节点是否存在，不存在将此节点安放在根节点处
        $sql = "SELECT cid, cname FROM $tbl_main WHERE cid = '{$result['pid']}' ";
        $rs = $conn->GetOne($sql);
        if(!$rs) $pid    = 0;


        // 同一个父节点下判断是否存在同名节点
        $sql = "SELECT COUNT(*) AS rs_count FROM $tbl_main WHERE pid = '{$result['pid']}' AND cname = '{$result['cname']}' AND cid <> '{$result['cid']}' ";
        $rs = $conn->GetOne($sql);
        if($rs) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                '父节点下已经存在名为<FONT COLOR=\"red\">' . $result['cname'] . '</FONT>的分类，无法当前修改操作！', 
                __FILE__,
                __LINE__);
            return false;
        }


        // +--------------------------------------------+ //
        // 处理修改时更换图片/删除图片时 删除原始图片
        $del_oldimg = 0;
        if($result['delimg'] == 1) {
            $result['img'] = '';
            $result['imgaid'] = 0;
            $del_oldimg = 1;
        } else {
            if($result['img'] != '') {
                $del_oldimg = 1;
            } else {
                unset($result['img']);
                unset($result['imgaid']);
            }
        }
        if($del_oldimg == 1) {
            // 取得当前修改分类的图片信息，如果存在则删除
            // 查找附件表，找到当前附件 不删除文件也不清楚附件记录
            $sql    = "UPDATE $tbl_ass1 SET item_id = 0
                        WHERE upmod = '$mod' 
                          AND upvar='classimg' 
                          AND item_id = '{$result['cid']}'";
            $conn->Execute($sql);
        }
        // +--------------------------------------------+ //

        // 得到一级栏目ID
        // 只要不是新增一级栏目都可以用父id得到一级栏目ID
        $result['cata_id'] = find_onelevel_id($result['cid'], $GLOBALS[$class_var]);
        // 修改分类的时候有这种情况，
        // 如果修改了父分类，特别是把一个子分类移动到另外一个“一级栏目”下，栏目ID就会出问题
        // 这里暂时不知道怎么解决!!!!
        // 不是十分严密的时候可以在分类列表生成分类缓存的时候做。
        if($conn->AutoExecute($tbl_main,$result,'UPDATE', 'cid=' . $result['cid'] . '')) {
            if(@(int)$result['imgaid'] > 0) {
                $conn->Execute("UPDATE $tbl_ass1 SET item_id = '{$result['cid']}' WHERE aid = '{$result['imgaid']}' ");
            }
            class_cache();
            return $result['cid'];
        }
    }
    return false;
}



function cdel() {
    global $_TABLES, $timestamp, $class_var, $cata;
    $tbl_main   = $_TABLES['article_class'];
    $tbl_ass1   = $_TABLES['article'];
    $tbl_ass2   = $_TABLES['attachments'];

    $cid = @(int)$_GET['cid'];
    // 如果有$cata参数传入，不能删除第一个节点
    if($cata > 0 && $cid == $cata) {
        // 不能删除当前分类的根节点
        $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                '该栏目为主栏目，无法完成删除操作！', 
                __FILE__,
                __LINE__);
        $GLOBALS['js_error'] = 1;
        return false;
    }
    if($cid > 0) {
        // 该分类及其下级分类中是否有文章
        $str_in = find_subnode_id($cid, $GLOBALS[$class_var]);
        $str_in.= $cid;

        $conn   = & get_db_conn();
        $sql    = "SELECT COUNT(*) AS rs_count FROM $tbl_ass1 WHERE cid IN ($str_in) ";
        $rs     = $conn->GetOne($sql);
        if($rs) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                '该栏目下或者其子栏目下还存在内容，无法完成删除操作！', 
                __FILE__,
                __LINE__);
            //echo "<meta http-equiv='Content-Type'' content='text/html; charset=utf-8'>"; 
            //echo "<script charset='utf-8' type='text/javascript'>alert('该栏目下或者其子栏目下还存在内容，无法完成删除操作！');</script>";
            $GLOBALS['js_error'] = 1;
            return false;
        }

        if($GLOBALS['js_error'] == 0) {
            // 更新当前表中的附件状态
            // 查找当前分类中的图片id
            $attachid   = '';
            $sql    = "SELECT imgaid FROM $tbl_main WHERE cid IN ($str_in) ";
            $rs = $conn->Execute($sql);
            $rs = $rs->GetRows();
            foreach($rs as $v) {
                $aid = @(int)$v['imgaid'];
                if($aid > 0) $attachid  .= $aid . ',';
            }
            if($attachid != '') {
                $attachid   = substr($attachid, 0, strlen($attachid)-1);
                $conn->Execute("UPDATE $tbl_ass2 SET item_id = '0' WHERE aid IN ($attachid) ");
            }


            $update_sql = "DELETE FROM $tbl_main WHERE cid IN ($str_in) ";
            if($conn->Execute($update_sql)) {
                // 删除成功
                class_cache();
                reload_parentframe('删除栏目成功！');
                exit();
            }
        }
    }
    exit();
}
?>